<?php

namespace App\Http\Repository;

use App\Sort;
use App\Chunk;

class SortRepository
{
    private $sort;
    private $chunk;

    public function __construct(Sort $sort, Chunk $chunk)
    {
        $this->sort = $sort;
        $this->chunk = $chunk;
    }

    //得到信息分类的多级分类
    public function getSortsByX($chunkId)
    {
        $tmpSorts = $this->sort
            ->where('chunk', $chunkId)
            ->select('id', 'name', 'parent', 'path', 'xindex')
            ->orderBy('xindex', 'DESC')
            ->get()
            ->toArray();
        $sorts = createTree($tmpSorts);

        return $sorts;
    }

    //得到按模块分组的分类信息
    public function getSortGroupChunk()
    {
        $chunks = $this->chunk
            ->where('status', 1)
            ->lists('path', 'id');
        $sorts = [];
        foreach ($chunks as $id => $chunk) {
            $tmpSorts = $this->sort
                ->where('sorts.status', 1)
                ->where('chunk', $id)
                ->join('chunks', 'chunks.id', '=', 'sorts.chunk')
                ->leftjoin('images', 'images.id', '=', 'sorts.image')
                ->select('sorts.*', 'images.path as image', 'chunks.path as chunk', 'sorts.created_at as time')
                ->orderBy('xindex', 'DESC')
                ->get()
                ->toArray();

            $sorts[$chunk] = createTree($tmpSorts);
        }

        foreach ($sorts as $chunk => $value) {
            $sortsWithid[$chunk] = [];
            foreach ($value as $sort) {
                $sortsWithid[$chunk][$sort['id']] = $sort;
            }
        }
        return $sortsWithid;
    }

    //得到用户可以发布讯息的信息分类的多级分类
    public function getSortsByXUserCanWrite($chunkId)
    {
        $tmpSorts = $this->sort
            ->where('chunk', $chunkId)
            ->where('user_write', 1)
            ->select('id', 'name', 'parent', 'path', 'xindex')
            ->orderBy('xindex', 'DESC')
            ->get()
            ->toArray();
        $sorts = createTree($tmpSorts);

        return $sorts;
    }
}